<?php
$dbname="172.16.250.169/orcl";
$dbuser="libsys";
$dbpassword="libsys";
$campusapp_redirecturl="https://wx.ccom.edu.cn/wap/proxy";
$campusapp_source="library";
$campusapp_key="i3pwYW8asEhr";

function _process_orcale_asciistr($str) {
        return preg_replace_callback(
                '|\\\([0-9A-F]{4})|',
                function ($matches) {
                        return mb_convert_encoding('&#'.intval('0x'.$matches[1],0).';', 'UTF-8', 'HTML-ENTITIES');
                },
                $str);
}

/* Internal function used in campusapp */
function campusapp_formatBizQueryParamMap($paramMap, $urlencode = false)
{
        $buff = "";
        foreach ($paramMap as $k => $v)
        {
                if ($v === "" || $v === null) continue;
                if($urlencode)
                {
                   $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
        }
        $reqPar = '';
        if (strlen($buff) > 0)
        {
                $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
}

function campusapp_getSign($Parameters, $key='')
{
        ksort($Parameters);
        $String = campusapp_formatBizQueryParamMap($Parameters, false);
        $String = $String."&key=".$key;
        $String = md5($String);
        $result = strtoupper($String);
        return $result;
}

header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
header("Pragma: no-cache");

if($_SERVER['REQUEST_METHOD']=='GET') { // About to display qrcode at frontend.
  if(empty($_GET['xgh'])||empty($_GET['realname'])||empty($_GET['signature'])) $should_redirect=1;
  $data=['xgh'=>$_GET['xgh'], 'realname'=>$_GET['realname']];
  if(campusapp_getSign($data, $campusapp_key)!==$_GET['signature']) $should_redirect=1;
  session_start();
  if(!isset($_SESSION['nonce'])||$_SESSION['nonce']!=$_GET['nonce']) $should_redirect=1;

  if($should_redirect==1) {
	$nonce=mt_rand();
	session_start();
	$_SESSION['nonce'] = $nonce;
	$data=['source'=>$campusapp_source, 'url'=>sprintf('%s://%s%s?nonce=%s',$_SERVER['HTTPS']?'https':'http',$_SERVER['HTTP_HOST'],$_SERVER['PHP_SELF'], $nonce)];
        $url=sprintf('Location: %s?source=%s&url=%s&signature=%s', $campusapp_redirecturl, $campusapp_source, urlencode($data['url']), campusapp_getSign($data, $campusapp_key));
        header($url, TRUE, 302);
        die;
  }
} elseif ($_SERVER['REQUEST_METHOD']=='POST') { // Decode userid from qrcode

  $rawinput=json_decode(file_get_contents("php://input"), TRUE);
  if(empty($rawinput['auth_code'])) {
    $output=['error_code'=>40001, 'error_message'=>'Bad input.'];
  } elseif(array_key_exists('version', $rawinput) && $rawinput['version']!==1.0) {
    $output=['error_code'=>40001, 'error_message'=>'Bad input.'];
  } else {
    $timeinput=getdate();
    $auth_code=json_decode(base64_decode($rawinput["auth_code"]), TRUE);
    $cryptedmsg=$auth_code['ciphertext'];
    $iv=hex2bin($auth_code['iv']);

    $time=getdate();
    $timestamp=mktime($time['hours'], $time['minutes'], 0)*1000;

    $key = hash_pbkdf2("sha512", (string)$timestamp, hex2bin(''), 999, 64);

    $tried_times=0;
    do {
	$key = hash_pbkdf2("sha512", (string)$timestamp, hex2bin(''), 999, 64);
	$result=openssl_decrypt($auth_code['ciphertext'], 'aes-256-cbc', hex2bin($key), 0, $iv);
	if($result===FALSE) {
		$tried_times++;
		if($tried_times==1) {
			$timestamp-=60000;
		} elseif($tried_times==2) {
			$timestamp+=120000;
		} elseif($tried_times>2) {
			break;
		}
	}
    } while (empty($result));

    if($result==FALSE) {
	if(array_key_exists('signature', $rawinput))
		$output=['code'=>1001, 'message'=>'Auth_code expired.'];
	else
		$output=['error_code'=>40002, 'error_message'=>'Auth_code expired.'];
    }
    else {
	if(array_key_exists('signature', $rawinput))
		$output=['code'=>0, 'user' => ['card_number'=>$result]];
	else
		$output=['error_code'=>0, 'user_id'=>$result];
    }
  }
  echo json_encode($output);

  exit;
}

?>
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,viewport-fit=cover">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="0" />
    <title>电子读者卡</title>
    <script src="//cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script src="qrcode.min.js"></script>
    <script src="//cdn.bootcss.com/crypto-js/3.1.9-1/crypto-js.js"></script>
    <script src="//res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
    <style>
#qrcode > img {
    display: block;
    margin: auto;
}
    </style>
<?php
if(preg_match('/wxwork\//', $_SERVER['HTTP_USER_AGENT'])) {
?>
    <link rel="stylesheet" href="//res.wx.qq.com/open/libs/weui/1.1.4/weui-for-work.min.css"/>
<?php
} else {
?>
    <link rel="stylesheet" href="//res.wx.qq.com/open/libs/weui/2.3.0/weui.min.css"/>
<?php
}
?>
</head>
<body>
<div class="page msg_success js_show">
	<div class="weui-msg">
	<div class="weui-msg__text-area">
		<div id="qrcode"></div>
		<h2 class="weui-msg__title"><?php echo sprintf("%s (%s) ",$_GET['realname'], $_GET['xgh']); ?></h2>
		<p class="weui-msg__desc"><span id="countdown"></span>秒后自动刷新 <a href="#" id="refreshLink" title="立即刷新">&#128260;</a></p>
	</div>
	<div class="weui-msg__extra-area">
		<div class="weui-footer"><p class="weui-footer__links"><a href="https://eaiapp.ccom.edu.cn/site/center/switch" class="weui-footer__link">如需切换身份请点击此处</a></p></div>
	</div>
	</div>
</div>
<script type="text/javascript">
var qrcode=new QRCode("qrcode", {
	width: Math.min($(window).width(),$(window).height())*0.5,
	height: Math.min($(window).width(),$(window).height())*0.5,
	colorDark : "#000000",
	colorLight : "#ffffff",
	correctLevel : QRCode.CorrectLevel.H
});

var timeout=0;
var redrawTimeout=0;
var iv = CryptoJS.lib.WordArray.random(16);
function drawQrcode() {
	var id="<?php echo $_GET['xgh'];?>";

	var timestampDate=new Date();
	if(timestampDate.getSeconds()>30) timestampDate.setMinutes++;
	timestampDate.setSeconds(0);
	timestampDate.setMilliseconds(0);
	var timestamp = Date.parse(timestampDate);

	var key = CryptoJS.PBKDF2(String(timestamp), '', { hasher: CryptoJS.algo.SHA512, keySize: 64/8, iterations: 999 });

	var encrypted = CryptoJS.AES.encrypt(id, key, {iv: iv});

	var data = {
		ciphertext : CryptoJS.enc.Base64.stringify(encrypted.ciphertext),
		iv : CryptoJS.enc.Hex.stringify(iv),
	}

	qrcode.clear();
	var code=CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(JSON.stringify(data)));
	qrcode.makeCode(code);
	//qrcode.makeCode(encrypted.ciphertext);
	clearTimeout(timeout);
	clearTimeout(redrawTimeout);
	redrawTimeout=setTimeout("drawQrcode()", 60000);
	$("#countdown").text("60");
	timeout=setTimeout("refreshCountDown()", 1000);
}

function refreshCountDown() {
	$("#countdown").text($("#countdown").text()-1);
	timeout=setTimeout("refreshCountDown()", 1000);
}

$(function(){
	drawQrcode();
	$("#refreshLink").click(function (event) {
		iv = CryptoJS.lib.WordArray.random(16);
		drawQrcode();
		event.preventDefault();
	});
});
</script>
</body>
</html>
